package com.eeepay.eeepay_v2.activity;

import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.IntoProAdapter;
import com.eeepay.eeepay_v2.model.IntoPiecesInfo;
import com.eeepay.eeepay_v2.model.LimitInfo;
import com.eeepay.eeepay_v2.model.MccType;
import com.eeepay.eeepay_v2.model.PaperFile;
import com.eeepay.eeepay_v2.model.ProductInfo;
import com.eeepay.eeepay_v2.model.RateInfo;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.BtnStyleUtil;
import com.eeepay.eeepay_v2.util.ConfigPorperties;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.DataUtils;
import com.eeepay.eeepay_v2.util.FormatUtil;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.SPUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.util.ABRegUtil;
import com.eeepay.v2_library.util.ScreenSwitch;
import com.eeepay.v2_library.view.LabelEditText;
import com.eeepay.v2_library.view.TitleBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.MerAddModular;
import cn.eeepay.api.grpc.nano.MerAddServiceGrpc;
import io.grpc.ManagedChannel;

/**
 * Created by Ching on 2016/3/3.
 * 进件页面
 */
public class IntoPiecesActivity extends ABBaseActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener, TitleBar.LeftBtnOnClickListener, AdapterView.OnItemClickListener {

    private RadioGroup radioGroup;//个体、商户选择
    private RadioGroup typeRgp;//商户类型
    private TitleBar titleBar;
    private LinearLayout typeLayout;
    private LabelEditText phoneLet, snoLet;//商户手机号、SN号
    private Button nextBtn;
    private ListView merchantLv, personLv;

    private List<ProductInfo> perList;//业务产品--个人
    private List<ProductInfo> merPerList;//业务产品--商户
    private List<ProductInfo> merBisList;//业务产品--商户
    private List<RateInfo> rateList;
    private List<LimitInfo> limitList;
    private List<PaperFile> fileList;
    //    private MerAddModular.ServiceInfo[] serviceInfos;
    private IntoProAdapter perAdapter;
    private IntoProAdapter mPerAdapter;
    //    private IntoProAdapter mBissAdapter;
    private ProductInfo productInfo;
    private EditListener listener;

    private IntoPiecesInfo intoPieces;
    private String merchantType = "1";
    private int type = 0;
    private String sn;
    private final int PERSON = 1;//个人
    private final int MERCAHNT_PER = 2;//个体商户
    private final int MERCAHNT_BIS = 3;//企业商户
    private final int DEVICE = 4;//校验机具
    private final int SERVICE = 5;//获取服务等进件信息
    private final int snLength = 16;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_into_pieces;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.tb_into_prieces);
//        titleBar.setShowRight(View.VISIBLE);
//        titleBar.setRightTextView("说明");
//        titleBar.setRightTextColor(R.color.blue);

        radioGroup = getViewById(R.id.rg_into_type);
        typeRgp = getViewById(R.id.rgp_into_merchant_type);
        typeLayout = getViewById(R.id.ll_into_merchant);
        phoneLet = getViewById(R.id.let_merchant_phone);
        phoneLet.getEditText().setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        snoLet = getViewById(R.id.let_sno);
        personLv = getViewById(R.id.lv_into_person);
        merchantLv = getViewById(R.id.lv_into_merBis);
        nextBtn = getViewById(R.id.btn_into_next);
        //add by zhuangzeqin 2017年4月17日09:33:55
        BtnStyleUtil.inintBtnDefaultStyle(mContext, nextBtn);
    }

    @Override
    protected void eventOnClick() {
        perList = new ArrayList<>();
        merBisList = new ArrayList<>();
        merPerList = new ArrayList<>();

        perAdapter = new IntoProAdapter(this);
        mPerAdapter = new IntoProAdapter(this);
        titleBar.setLeftOnClickListener(this);

        typeRgp.setOnCheckedChangeListener(this);
        typeRgp.getChildAt(0).performClick();//初次默认点击第一个按钮

        radioGroup.setOnCheckedChangeListener(this);
        radioGroup.getChildAt(0).performClick();//初次默认点击第一个按钮

//        CheckUtils.addEditChangeListener(nextBtn, R.drawable.icon_next_step, R.drawable.icon_no_next_step, phoneLet, snoLet);
        listener = new EditListener();
        snoLet.getEditText().addTextChangedListener(listener);
        phoneLet.getEditText().addTextChangedListener(listener);

        nextBtn.setOnClickListener(this);
//        sendHttpRequest(PERSON);

        personLv.setAdapter(perAdapter);
        merchantLv.setAdapter(mPerAdapter);
        personLv.setOnItemClickListener(this);
        //商户进件的时候如果用户手机号 填写格式不对，则toast提示“请填写正确的手机号”
        phoneLet.getEditText().setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // 此处为失去焦点时的处理内容
                if (hasFocus==false) {
                    if(!TextUtils.isEmpty(phoneLet.getEditContent()) && !ABRegUtil.isRegiest(phoneLet.getEditContent(), ABRegUtil.REG_PHONE_CHINA)){
                        showToast("请填写正确的手机号");
                        return;
                    }
                }
            }
        });

        //机具SN号不对则提示“请填写正确的SN号”
        snoLet.getEditText().setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus==false)
                {
                    if (ABRegUtil.isRegiest(snoLet.getEditContent(),ABRegUtil.REG_STRING))
                    {
                        showToast("机具SN号不包括中文字符,请重新输入");
                        snoLet.getEditText().setText("");
                        snoLet.getEditText().clearFocus();
                        return;
                    }
                    else if (FormatUtil.checkStringContainChinese(snoLet.getEditContent()))
                    {
                        showToast("机具SN号不包括中文字符,请重新输入");
                        snoLet.getEditText().setText("");
                        snoLet.getEditText().clearFocus();
                        return;
                    }
                    //sn 号判断长度
                    else if (!TextUtils.isEmpty(sn) && sn.length() != snLength)
                    {
                        showToast("请填写正确的SN号");
                        snoLet.getEditText().setText("");
                        snoLet.getEditText().clearFocus();
                        return;
                    }
                }
            }
        });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        productInfo = (ProductInfo) parent.getAdapter().getItem(position);

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        sn = snoLet.getEditContent();
        productInfo = null;
        switch (checkedId) {
            case R.id.rbtn_person://个人
                personLv.setVisibility(View.VISIBLE);
                typeLayout.setVisibility(View.GONE);
                merchantType = "1";
                type = 0;
                if (!TextUtils.isEmpty(sn) && sn.length() == snLength)
                    sendHttpRequest(PERSON);
//                if (perList == null && perList.size() == 0) {
//                    perAdapter.addAll(p+erList);
//                } else if (perAdapter.getDatas() != null) {
//                    perAdapter.removeAll();
//                    perAdapter.addAll(perList);
//                    Log.d("proInfo", "rbtn_person");
//                }
//                productLv.setAdapter(perAdapter);
                break;
            case R.id.rbtn_merchant://商户
                typeLayout.setVisibility(View.VISIBLE);
                personLv.setVisibility(View.GONE);
                type = 1;
                typeRgp.getChildAt(0).performClick();
                break;
            case R.id.rbtn_bis_merchant://企业商户
                merchantType = "3";
//                if (merBisList == null) {
//                    sendHttpRequest(MERCAHNT_BIS);
////                    Log.d("proInfo", "merBisList == null");
//                }
                if (!TextUtils.isEmpty(sn) && sn.length() == snLength) {
                    sendHttpRequest(MERCAHNT_BIS);
                } else {
                    merBisList.clear();
                }
                if (merBisList != null) {
//                    mPerAdapter.removeAll();
//                    mPerAdapter.addAll(merBisList);
                    mPerAdapter.setList(merBisList);
//                    Log.d("proInfo", "rbtn_bis_merchant");
                }
//                productLv.setAdapter(mBissAdapter);
                break;
            case R.id.rbtn_person_merchant://个人商户
                merchantType = "2";
//                if (merPerList == null) {
//                    sendHttpRequest(MERCAHNT_PER);
//                }
                if (!TextUtils.isEmpty(sn) && sn.length() == snLength) {
                    sendHttpRequest(MERCAHNT_PER);
                } else {
                    merPerList.clear();
                }
                if (merPerList != null && merPerList.size() > 0) {
                    mPerAdapter.setList(merPerList);
                }
                break;
        }
        checkData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_into_next:
//                Log.d("proInfo", " merchantType--> " + merchantType);
                switch (Integer.parseInt(merchantType)) {
                    case PERSON:
                        productInfo = perAdapter.getProInfo();
                        break;
                    case MERCAHNT_PER:
                    case MERCAHNT_BIS:
                        productInfo = mPerAdapter.getProInfo();
                        break;
//                        productInfo = mPerAdapter.getProInfo();
//                        break;
                }
                if (productInfo.getProId() == null) {
                    showToast("请输入正确的机具SN号以获取业务产品");
                    return;
                }
                if (ABRegUtil.isRegiest(phoneLet.getEditContent().trim(), ABRegUtil.REG_PHONE_CHINA)) {
                    // sendHttpRequest(DEVICE); add by zhuangzeqin 2017年4月19日15:51:14 取消checkRegistRules这个接口的调用。
                    sendHttpRequest(SERVICE);
                } else {
                    showToast("手机号不正确");
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog("请稍等。。。");
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT, taskId, new GrpcUtils.AsyncTaskListener() {
                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        MerAddServiceGrpc.MerAddServiceBlockingStub stub = MerAddServiceGrpc.newBlockingStub(channel)
                                .withDeadlineAfter(5, TimeUnit.SECONDS);
                        MerAddModular.ProductReq productReq = new MerAddModular.ProductReq();
                        UserInfo userInfo = UserInfo.getInstance();
                        productReq.agentNo = userInfo.getAgentNo();
                        productReq.bpType = snoLet.getEditContent();
                        switch (taskId) {
                            case DEVICE:
                                MerAddModular.RegistRulesReq regRequest = new MerAddModular.RegistRulesReq();
//                                regRequest.agentNo = userInfo.getAgentNo();
                                regRequest.mobilephone = phoneLet.getEditContent().trim();
                                regRequest.teamId = ConfigPorperties.getInstance().getTeamId();
//                                regRequest.bpId = productInfo.getProId();
//                           regRequest.sn = intoPieces.getSno();
                                return stub.checkRegistRules(regRequest);
                            case SERVICE:
                                Log.d("intoSer", "请求SERVICE");
                                MerAddModular.GetServiceReq request = new MerAddModular.GetServiceReq();
//                                request.agentNo = "10000";
//                                request.oneAgentNo = "0";
                                if (productInfo != null) {
//                                    Log.d("intoPiece", " bpid--> " + productInfo.getProId());
                                    request.bpId = productInfo.getProId();
                                    request.agentNo = userInfo.getAgentNo();
                                    request.oneAgentNo = userInfo.getOneAgentNo();
                                    //add by zhuangzeqin 2017年4月19日15:19:01 增加参数mobilephone
                                    request.mobilephone = phoneLet.getEditContent().trim();
                                    return stub.getServiceInfoByParams(request);
                                }
                            case PERSON://个人
                                productReq.bpType = "1";
                                productReq.sn = snoLet.getEditContent().trim();
                                return stub.getMerProductList(productReq);
                            case MERCAHNT_PER://个体商户
                                productReq.bpType = "2";
                                productReq.sn = snoLet.getEditContent().trim();
                                return stub.getMerProductList(productReq);
                            case MERCAHNT_BIS://企业商户
                                productReq.bpType = "3";
                                productReq.sn = snoLet.getEditContent().trim();
                                return stub.getMerProductList(productReq);
                        }
                        return null;
                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        dismissProgressDialog();
                        MerAddModular.ProductResList response;
//                if (result == null) {
//                    showToast("查询失败");
//                    return;
//                }
                        switch (taskId) {
                            case DEVICE://验证设备使用情况
                                MerAddModular.MyResponse devResponse = (MerAddModular.MyResponse) result;
                                if (result == null) {
                                    showToast("机具校验失败，请重试");
//                                    finish();
                                    return;
                                }
                                if (!devResponse.resMsg.status) {
                                    showToast(devResponse.resMsg.msg.toString());
                                    return;
                                }
                                if (devResponse.resMsg.status) {//成功
                                    sendHttpRequest(SERVICE);
                                }
                                break;
                            case SERVICE://处理获取服务返回的结果
                                Log.d("intoSer", "处理获取服务返回的结果");
                                MerAddModular.MyResponse serResponse = (MerAddModular.MyResponse) result;
                                if (result == null) {
                                    showToast("获取进件项失败，请重试");
                                    return;
                                } else if (serResponse.resMsg.status) {//成功
                                    getService(serResponse);
                                } else if (!serResponse.resMsg.status) {
                                    showToast(serResponse.resMsg.msg);
                                }
                                break;
                            case PERSON:
                                response = (MerAddModular.ProductResList) result;
                                if (result == null) {
                                    showToast("获取个人业务产品失败");
                                    return;
                                } else if (response.resMsg.status) {//成功
                                    MerAddModular.ProductInfo[] personArray = response.productInfo;
                                    MerAddModular.ProductInfo person;
                                    if (perList != null)
                                        perList.clear();
                                    for (int i = 0; i < personArray.length; i++) {
                                        person = personArray[i];
                                        perList.add(new ProductInfo(person.bpId, person.bpName,
                                                person.remark, null));
                                    }
                                    if (perList.size() > 0) {
                                        perAdapter.setList(perList);
                                        productInfo = perList.get(0);
                                        if (!TextUtils.isEmpty(phoneLet.getEditContent())
                                                && !TextUtils.isEmpty(snoLet.getEditContent())
                                                && productInfo != null) {
                                            BtnStyleUtil.settingBtnStyle(mContext, nextBtn);
//                                            nextBtn.setEnabled(true);
//                                            nextBtn.setBackgroundResource(R.drawable.icon_next_step);
                                        } else {

                                            BtnStyleUtil.inintBtnDefaultStyle(mContext, nextBtn);
//                                            nextBtn.setEnabled(false);
//                                            nextBtn.setBackgroundResource(R.drawable.icon_no_next_step);
                                        }
                                    }
                                } else if (!response.resMsg.status) {
                                    perAdapter.removeAll();
                                    showToast(response.resMsg.msg);
                                }
//                            Log.d("proInfo", " 所选项：名称 " + person.bpName + "| 产品ID: " + person.bpId
//                                    + "| 说明：" + person.remark + "| " + person.bpType + "| " + person.proxy
//                            );
//                                productInfo =  perAdapter.getProInfo();
//                                if (!TextUtils.isEmpty(phoneLet.getEditContent())
//                                        && !TextUtils.isEmpty(snoLet.getEditContent())
//                                        && productInfo != null) {
//                                    nextBtn.setEnabled(true);
//                                    nextBtn.setBackgroundResource(R.drawable.icon_next_step);
//                                } else {
//                                    nextBtn.setEnabled(false);
//                                    nextBtn.setBackgroundResource(R.drawable.icon_no_next_step);
//                                }
//                                checkData();

                                break;
                            case MERCAHNT_PER:
                                response = (MerAddModular.ProductResList) result;
                                if (result == null) {
                                    showToast("获取个体商户业务产品失败");
                                    return;
                                } else if (response.resMsg.status) {//成功
                                    MerAddModular.ProductInfo[] merPerArray = response.productInfo;
                                    MerAddModular.ProductInfo merPerInfo;
                                    if (merPerList != null)
                                        merPerList.clear();
                                    for (int i = 0; i < merPerArray.length; i++) {
                                        merPerInfo = merPerArray[i];
                                        merPerList.add(new ProductInfo(merPerInfo.bpId, merPerInfo.bpName,
                                                merPerInfo.remark, null));
                                    }
                                    if (merPerList.size() > 0) {
                                        mPerAdapter.setList(merPerList);
                                        productInfo = merPerList.get(0);
                                        if (!TextUtils.isEmpty(phoneLet.getEditContent())
                                                && !TextUtils.isEmpty(snoLet.getEditContent())
                                                && productInfo != null) {
                                            BtnStyleUtil.settingBtnStyle(mContext, nextBtn);
//                                            nextBtn.setEnabled(true);
//                                            nextBtn.setBackgroundResource(R.drawable.icon_next_step);
                                        } else {
                                            BtnStyleUtil.inintBtnDefaultStyle(mContext, nextBtn);
//                                            nextBtn.setEnabled(false);
//                                            nextBtn.setBackgroundResource(R.drawable.icon_no_next_step);
                                        }
                                    }
                                } else if (!response.resMsg.status) {
                                    perAdapter.removeAll();
                                    showToast(response.resMsg.msg);
                                }
//                            Log.d("proInfo", " 所选项：名称 " + merPerInfo.bpName + "| 产品ID: " + merPerInfo.bpId
//                                    + "| 说明：" + merPerInfo.remark + "| 产品类型：" + merPerInfo.bpType
//                            );
//                                checkData();
//                                typeRgp.getChildAt(1).performClick();
                                break;
                            case MERCAHNT_BIS:
                                response = (MerAddModular.ProductResList) result;
                                if (result == null) {
                                    showToast("获取个体商户业务产品失败");
                                    return;
                                } else if (response.resMsg.status) {//成功
                                    MerAddModular.ProductInfo[] merBisArray = response.productInfo;
                                    MerAddModular.ProductInfo merBisInfo;
                                    if (merBisList != null)
                                        merBisList.clear();
                                    for (int i = 0; i < merBisArray.length; i++) {
                                        merBisInfo = merBisArray[i];
                                        merBisList.add(new ProductInfo(merBisInfo.bpId, merBisInfo.bpName,
                                                merBisInfo.remark, null));
                                    }
                                    if (merBisList.size() > 0) {
                                        mPerAdapter.setList(merBisList);
                                        productInfo = merPerList.get(0);
                                        if (!TextUtils.isEmpty(phoneLet.getEditContent())
                                                && !TextUtils.isEmpty(snoLet.getEditContent())
                                                && productInfo != null) {
                                            BtnStyleUtil.settingBtnStyle(mContext, nextBtn);
//                                            nextBtn.setEnabled(true);
//                                            nextBtn.setBackgroundResource(R.drawable.icon_next_step);
                                        } else {
                                            BtnStyleUtil.inintBtnDefaultStyle(mContext, nextBtn);
//                                            nextBtn.setEnabled(false);
//                                            nextBtn.setBackgroundResource(R.drawable.icon_no_next_step);
                                        }
                                    }
                                } else if (!response.resMsg.status) {
                                    perAdapter.removeAll();
                                    showToast(response.resMsg.msg);
                                }
//                            Log.d("proInfo", "企业商户--> 所选项：名称 " + merBisInfo.bpName + "| 产品ID: " + merBisInfo.bpId
//                                    + "| 说明：" + merBisInfo.remark + "| 产品类型：" + merBisInfo.bpType
//                            );
//                                typeRgp.getChildAt(1).performClick();
                                break;
                        }
//                        checkData();
                    }
                }
        );
    }

    /**
     * @param response 获取服务器返回的进件项等
     */
    public void getService(MerAddModular.MyResponse response) {
        MerAddModular.AddRequireItem[] itemArr = response.addRequireItem;
        MerAddModular.ServiceRate[] rateArr = response.serviceRate;
        MerAddModular.ServiceQuota[] quotaArr = response.serviceQuota;
        MerAddModular.MerType[] merTypeArr = response.merType;
        intoPieces = new IntoPiecesInfo();

        DataUtils.getInstance().setSerInfoArray(response.serviceInfo);
        MerAddModular.MerType merType;
        List<MccType> typeList = new ArrayList<>();
        String industry = null;
        String mcc = null;
        Map<String, List<MccType>> datas = new HashMap<>();
        for (int i = 0; i < merTypeArr.length; i++) {//商户类别一级
            merType = merTypeArr[i];
            typeList.add(new MccType(merType.sysName, merType.sysValue));
            List<MccType> mccTypeList = new ArrayList<>();
            for (int j = 0; j < merType.merMccType.length; j++) {//商户类别二s级
                MerAddModular.MerMccType mccType = merType.merMccType[j];
                MccType mccT = new MccType(mccType.sysName, mccType.sysValue);
                mccTypeList.add(mccT);
                if (i == 0 && j == 0) {
                    industry = mccType.sysName;
                    mcc = mccType.sysValue;

                }
//                Log.d("merType", "merType: MccType->" + mccType.sysName + "-" + mccType.sysValue);
            }
            datas.put(merType.sysName, mccTypeList);
        }
        //设置默认的商户类别
        if (intoPieces != null && typeList.size() > 0) {
            intoPieces.setBisType(typeList.get(0).getSysName());
            intoPieces.setBisTypeNo(typeList.get(0).getSysValue());
            intoPieces.setIndustry(merTypeArr[0].merMccType[0].sysName);
            intoPieces.setMcc(merTypeArr[0].merMccType[0].sysValue);
//            Log.d("merType", "默认: Industry->" + intoPieces.getIndustry()
//                    + "   BisType->" + intoPieces.getBisType());
//            DataUtils.getInstance().setMerType();
            SPUtils.saveIntoPieces(intoPieces);
        }
        SPUtils.saveList(typeList, Constant.KEY.MERTYPE);
        DataUtils.getInstance().setDatas(datas);

//        if (rateArr.length == 0 || quotaArr.length == 0) {
//            SPUtils.removeList(SPUtils.getList(Constant.KEY.PAPER_FILE).size(), Constant.KEY.PAPER_FILE);
////            Log.d("saki", "返回的数据为空");
//            return;
//        } else {
        /** 进件项照片 **/
        if (itemArr.length != 0) {
            fileList = new ArrayList<>();
            PaperFile file;
            MerAddModular.AddRequireItem addItem;
            for (int j = 0; j < itemArr.length; j++) {
                file = new PaperFile();
                addItem = itemArr[j];
                file.setFileName(addItem.itemId + ".png");
                file.setTipName(addItem.itemName);
                file.setItemId(addItem.itemId);
                file.setPhoto(addItem.photo);
                file.setRemark(addItem.remark);
//                Log.d("saki", " itemId: " + addItem.itemId);
                fileList.add(file);
            }
            SPUtils.removeList(SPUtils.getList(Constant.KEY.PAPER_FILE).size(), Constant.KEY.PAPER_FILE);
            SPUtils.saveList(fileList, Constant.KEY.PAPER_FILE);
        }

        /** 费率 **/
        if (rateArr.length != 0) {
            rateList = new ArrayList<>();
            RateInfo rateInfo;
            MerAddModular.ServiceRate rate;
            for (int i = 0; i < rateArr.length; i++) {
                rateInfo = new RateInfo();
                rate = rateArr[i];
//                Log.d("saki", " rate: " + rate.rate + " 修改: " + rate.fixedRate
//                        + " 类型：" + rate.rateType);
                rateInfo.setServiceName(rate.serviceName);
                rateInfo.setCardType(rate.cardType);
                rateInfo.setServiceTime(rate.holidaysMark);
                rateInfo.setRateType(rate.rateType);
                rateInfo.setFixedRate(rate.fixedRate);
                rateInfo.setId(rate.id);
//                Log.d("merSerRate.id", " merSerRate.id:" +  rate.id);
                Log.d("saki", " rateType " + rate.fixedRate);
                switch (Integer.parseInt(rate.rateType)) {
                    case 1:
                        rateInfo.setSingle_num_amount(rate.singleNumAmount);
                        break;
                    case 2:
                        rateInfo.setRate(rate.rate);
                        break;
                    case 3:
                        rateInfo.setSafe_line(rate.safeLine);
                        rateInfo.setRate(rate.rate);
                        rateInfo.setCapping(rate.capping);
//                        Log.d("saki", " capping " + rate.capping);
                        break;
                    case 4:
                        rateInfo.setRate(rate.rate);
                        rateInfo.setSingle_num_amount(rate.singleNumAmount);
                        break;
                    case 5:
                        rateInfo.setLdr1Rate(rate.ladder1Rate);
                        rateInfo.setLdr1Max(rate.ladder1Max);
                        rateInfo.setLdr2Rate(rate.ladder2Rate);
//                        Log.d("saki", " type = 5 " + rate.ladder1Rate + "%<" + rate.ladder1Max + "<" + rate.ladder2Rate);
                        break;
                }
                rateInfo.setServiceId(rate.serviceId);
                rateList.add(rateInfo);
//                Log.d("saki", rateArr[i].agentNo + " | " + rateArr[i].serviceName + " | " + rateArr[i].holidaysMark);
            }
            SPUtils.saveList(rateList, Constant.KEY.RATE);
        }

        /** 限额 **/
        if (quotaArr.length != 0) {
            limitList = new ArrayList<>();
            LimitInfo limitInfo;
            MerAddModular.ServiceQuota quota;
            for (int k = 0; k < quotaArr.length; k++) {
                limitInfo = new LimitInfo();
                quota = quotaArr[k];
                limitInfo.setServiceId(quota.serviceId);
                limitInfo.setServiceName(quota.serviceName);
                limitInfo.setCardType(quota.cardType);
                limitInfo.setServiceTime(quota.holidaysMark);
                limitInfo.setMinAmount(quota.singleMinAmount);
                limitInfo.setDayAmount(quota.singleDayAmount);
                limitInfo.setCountAmount(quota.singleCountAmount);
                limitInfo.setDayCardAmount(quota.singleDaycardAmount);
                limitInfo.setDayCardConut(quota.singleDaycardCount);
                limitInfo.setFixedQuota(quota.fixedQuota);
                limitInfo.setId(quota.id);
                limitList.add(limitInfo);
//                Log.d("limit", "serviceName = " + quota.serviceName + " ||   singleDayAmount = " + quota.singleDayAmount +
//                        " ||   singleDaycardAmount " + quota.singleCountAmount + " ||   singleDaycardAmount = "
//                        + quota.singleDaycardAmount + " ||   singleDayAmount = " + quota.singleDaycardCount
//                        + " ||   singleMinAmount = " + quota.singleMinAmount
//                );
//                Log.d("limit", "fixedQuota = " + quota.fixedQuota);
            }
            SPUtils.saveList(limitList, Constant.KEY.LIMIT);
        }
//        }

        if (intoPieces != null) {
            intoPieces.setMerchantType(String.valueOf(merchantType));
            intoPieces.setMerPhone(phoneLet.getEditContent().trim());
            intoPieces.setSno(snoLet.getEditContent().trim());
            if (productInfo != null) {
                intoPieces.setProId(productInfo.getProId());
                intoPieces.setProName(productInfo.getProName());
            }
            SPUtils.saveIntoPieces(intoPieces);
            ScreenSwitch.switchActivity(this, CompleteDataActivity.class, null, 0);
        }
    }

    @Override
    public void onLeftClick(View view) {
        this.finish();
    }

    public void checkData() {
        switch (type) {
            case 0:
                productInfo = perAdapter.getProInfo();
                break;
            case 1:
//                switch (Integer.parseInt(merchantType)) {
////                    case PERSON:
////                        productInfo = perAdapter.getProInfo();
////                        break;
//                    case MERCAHNT_PER:
//                    case MERCAHNT_BIS:
                productInfo = mPerAdapter.getProInfo();
//                        break;
//                }
                break;
        }

        if (!TextUtils.isEmpty(phoneLet.getEditContent())
                && !TextUtils.isEmpty(snoLet.getEditContent())
                && productInfo != null
                && sn.length() == snLength) {
//            nextBtn.setEnabled(true);
//            nextBtn.setBackgroundResource(R.drawable.icon_next_step);
            BtnStyleUtil.settingBtnStyle(mContext, nextBtn);
        } else {
            BtnStyleUtil.inintBtnDefaultStyle(mContext, nextBtn);
//            nextBtn.setEnabled(false);
//            nextBtn.setBackgroundResource(R.drawable.icon_no_next_step);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { //按下的如果是BACK，同时没有重复
            onLeftClick(null);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    class EditListener implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            sn = snoLet.getEditContent();
            checkData();
            if (sn.length() == snLength) {
                switch (merchantType) {
                    case "1":
                        sendHttpRequest(PERSON);
                        break;
                    case "2":
                        sendHttpRequest(MERCAHNT_PER);
                        break;
                    case "3":
                        sendHttpRequest(MERCAHNT_BIS);
                        break;
                }
            } else {
                perAdapter.removeAll();
                mPerAdapter.removeAll();

            }
        }
    }

}

